package com.hbzhit.modules.oss.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.hbzhit.common.exception.RRException;
import com.hbzhit.common.utils.ConfigConstant;
import com.hbzhit.common.utils.PageUtils;
import com.hbzhit.common.utils.R;
import com.hbzhit.common.utils.ShiroUtils;
import com.hbzhit.common.validator.ValidatorUtils;
import com.hbzhit.common.validator.group.AliyunGroup;
import com.hbzhit.common.validator.group.QcloudGroup;
import com.hbzhit.common.validator.group.QiniuGroup;
import com.hbzhit.modules.oss.cloud.OSSFactory;
import com.hbzhit.modules.oss.config.CloudStorageConfig;
import com.hbzhit.modules.oss.config.OssProperties;
import com.hbzhit.modules.oss.entity.SysOssEntity;
import com.hbzhit.modules.oss.form.SysOssQueryForm;
import com.hbzhit.modules.oss.service.SysOssService;
import com.hbzhit.modules.sys.service.SysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 文件上传
 *
 * @author Mark sunlightcs@gmail.com
 */
@Api(tags = {"对象存储"})
@RestController
@RequestMapping("sys/oss")
@AllArgsConstructor
public class SysOssController {
	private final SysOssService sysOssService;
    private final SysConfigService sysConfigService;
	private final OssProperties ossProperties;

    private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;

	@ApiOperation(value = "查询分页数据")
	@GetMapping("/page")
	@RequiresPermissions("sys:oss:all")
	public R<PageUtils<SysOssEntity>> page(SysOssQueryForm params){
		PageUtils<SysOssEntity> page = sysOssService.queryPage(params);

		return R.ok(page);
	}

	@ApiOperation(value = "查询列表数据")
	@GetMapping("/list")
	public R<List<SysOssEntity>> list(SysOssQueryForm params){
		String idsStr = params.getIds() != null ? params.getIds() : "";
		List<String> ids = Arrays.asList(idsStr.split(","));

		List<SysOssEntity> list = sysOssService.list(new QueryWrapper<SysOssEntity>().lambda().in(CollectionUtil.isNotEmpty(ids), SysOssEntity::getId, ids));

		return R.ok(list);
	}

	@ApiOperation(value = "云存储配置信息")
    @GetMapping("/config")
    @RequiresPermissions("sys:oss:all")
    public R<CloudStorageConfig> config(){
        CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);

        return R.ok(config);
    }

	@ApiOperation(value = "保存云存储配置信息")
	@PostMapping("/saveConfig")
	@RequiresPermissions("sys:oss:all")
	public R saveConfig(@RequestBody CloudStorageConfig config){
		//校验类型
		ValidatorUtils.validateEntity(config);

		if(config.getType() == ConfigConstant.CloudService.QINIU.getValue()){
			//校验七牛数据
			ValidatorUtils.validateEntity(config, QiniuGroup.class);
		}else if(config.getType() == ConfigConstant.CloudService.ALIYUN.getValue()){
			//校验阿里云数据
			ValidatorUtils.validateEntity(config, AliyunGroup.class);
		}else if(config.getType() == ConfigConstant.CloudService.QCLOUD.getValue()){
			//校验腾讯云数据
			ValidatorUtils.validateEntity(config, QcloudGroup.class);
		}

        sysConfigService.updateValueByKey(KEY, new Gson().toJson(config));

		return R.ok();
	}

	@ApiOperation(value = "删除")
	@PostMapping("/delete")
	@RequiresPermissions("sys:oss:all")
	public R delete(@RequestBody Long[] ids){
		sysOssService.removeByIds(Arrays.asList(ids));

		return R.ok();
	}


	/**
	 * 上传文件
	 */
	@ApiOperation(value = "上传文件")
	@PostMapping("/upload")
	public R<SysOssEntity> upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}

		//上传文件
		String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
		String url = Objects.requireNonNull(OSSFactory.build()).uploadSuffix(file.getBytes(), suffix);

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setFileName(file.getOriginalFilename());
		ossEntity.setFileSize(file.getSize());
		ossEntity.setFileSuffix(suffix);
		ossEntity.setUrl(url);
		ossEntity.setCreator(ShiroUtils.getUserId());
		ossEntity.setCreateTime(new Date());
		sysOssService.save(ossEntity);

		return R.ok(ossEntity);
	}

	/**
	 * 下载文件
	 */
	@ApiOperation(value = "下载文件")
	@GetMapping("/download/{fileId}")
	public void download(@PathVariable("fileId") Long fileId, HttpServletResponse response) {
		try {
			SysOssEntity ossEntity = sysOssService.getById(fileId);

			File file = new File(ossProperties.getFileUploadConfig().getPath() + ossEntity.getUrl());
			//解决文件名中文乱码问题
			String filename = new String(ossEntity.getFileName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);

			response.setContentType("application/force-download");
			response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
			response.setHeader("Content-Length", String.valueOf(file.length()));

			byte[] buffer = new byte[1024];
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream bis = new BufferedInputStream(fis);
			OutputStream os = response.getOutputStream();

			int i = bis.read(buffer);
			while(i != -1){
				os.write(buffer);
				i = bis.read(buffer);
			}
		} catch (FileNotFoundException e) {
			throw new RRException("文件不存在", e);
		} catch (Exception e) {
			throw new RRException("下载文件失败", e);
		}
	}
}
